const express = require('express');
const router = express.Router();
const { pool } = require('../config/db');
const auth = require('../middleware/auth');

// 获取通知列表
router.get('/', async (req, res) => {
  try {
    console.log('通知公告路由被访问，参数:', req.query);
    const { userId, role, limit = 5, type = '' } = req.query;
    
    // 移除必须有userId的限制，允许不传userId参数
    // if (!userId) {
    //   return res.status(400).json({ message: '缺少必要参数' });
    // }
    
    // 查询用户角色
    let userRole = role;
    let userDepartment;
    let userClass;
    
    if (!userRole && userId) {
      const [userRows] = await pool.query('SELECT role, classId, department FROM users WHERE userId = ?', [userId]);
      if (userRows.length > 0) {
        userRole = userRows[0].role;
        userDepartment = userRows[0].department;
        userClass = userRows[0].classId;
        console.log(`查询到用户信息: 角色=${userRole}, 院系=${userDepartment}, 班级=${userClass}`);
      }
    }
    
    // 构建查询条件
    let query = `
      SELECT id, title, content, publishTime, publisherName as publisher, isImportant as importance
      FROM notices
      WHERE 1=1
    `;
    
    const params = [];
    
    // 根据角色筛选通知，如果有角色信息
    if (userRole) {
      // 使用JSON_CONTAINS函数检查targetRoles字段是否包含用户角色
      query += ` AND (JSON_CONTAINS(targetRoles, ?) OR targetRoles = '[]' OR targetRoles IS NULL)`;
      params.push(JSON.stringify(userRole));
    }
    
    // 如果用户有院系信息，筛选院系相关通知
    if (userDepartment) {
      query += ` AND (JSON_CONTAINS(targetDepartments, ?) OR targetDepartments = '[]' OR targetDepartments IS NULL)`;
      params.push(JSON.stringify(userDepartment));
    }
    
    // 如果用户有班级信息，筛选班级相关通知
    if (userClass) {
      // 查询班级ID
      const [classRows] = await pool.query('SELECT id FROM classes WHERE className = ?', [userClass]);
      if (classRows.length > 0) {
        const classId = classRows[0].id.toString();
        query += ` AND (JSON_CONTAINS(targetClasses, ?) OR targetClasses = '[]' OR targetClasses IS NULL)`;
        params.push(JSON.stringify(classId));
      }
    }
    
    // 如果指定了类型，添加类型过滤
    if (type && type !== 'all') {
      query += ` AND type = ?`;
      params.push(type);
    }
    
    // 添加排序和限制
    query += ` ORDER BY publishTime DESC LIMIT ?`;
    params.push(parseInt(limit));
    
    console.log('执行SQL查询:', query, params);
    
    const [rows] = await pool.query(query, params);
    console.log('通知公告查询结果:', rows);
    
    // 格式化日期并添加简短描述
    const formattedRows = rows.map(notice => {
      // 从内容中提取纯文本作为简短描述
      const brief = notice.content
        .replace(/<[^>]+>/g, '') // 移除HTML标签
        .substring(0, 100) + (notice.content.length > 100 ? '...' : '');
      
      // 检查是否有附件
      const hasAttachment = notice.attachments && 
                           notice.attachments !== '[]' && 
                           notice.attachments !== null;
      
      return {
        ...notice,
        brief,
        publishTime: new Date(notice.publishTime).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        }),
        hasAttachment: hasAttachment || false,
        isRead: true, // 暂时设为true，后续可以根据实际情况修改
        important: notice.importance > 0
      };
    });
    
    // 在响应中添加用户角色信息
    res.json({
      role: userRole || 'guest',
      notices: formattedRows
    });
  } catch (error) {
    console.error('获取通知公告失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 获取单个通知
router.get('/:id', async (req, res) => {
  try {
    const noticeId = req.params.id;
    console.log('通知详情路由被访问，通知ID:', noticeId);
    
    // 查询通知详情
    const query = `
      SELECT id, title, content, publishTime, publisherName as publisher, 
             isImportant as importance, attachments
      FROM notices
      WHERE id = ?
    `;
    
    const [rows] = await pool.query(query, [noticeId]);
    
    if (rows.length === 0) {
      return res.status(404).json({ message: '通知不存在' });
    }
    
    const notice = rows[0];
    
    // 格式化日期
    notice.publishTime = new Date(notice.publishTime).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
    
    // 解析附件
    try {
      notice.attachments = notice.attachments ? JSON.parse(notice.attachments) : [];
    } catch (e) {
      console.error('解析附件JSON失败:', e);
      notice.attachments = [];
    }
    
    // 添加其他必要字段
    notice.important = notice.importance > 0;
    notice.sender = notice.publisher; // 兼容前端字段
    notice.senderAvatar = '/images/default_avatar.png'; // 默认头像
    
    res.json(notice);
  } catch (error) {
    console.error('获取通知详情失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 添加文件上传配置
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 配置文件存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = path.join(__dirname, '..', 'uploads', 'notices');
    // 确保上传目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成文件名: 时间戳-原始文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ 
  storage: storage,
  limits: {
    fileSize: 10 * 1024 * 1024 // 限制文件大小为10MB
  }
});

// 文件上传接口
router.post('/upload', auth, upload.single('file'), async (req, res) => {
  try {
    // 验证用户是否为管理员
    if (req.user.role !== 'admin') {
      return res.status(403).json({
        success: false,
        message: '权限不足，只有管理员可以上传通知附件'
      });
    }

    if (!req.file) {
      return res.status(400).json({
        success: false,
        message: '未接收到文件'
      });
    }

    // 构建文件访问URL
    const fileUrl = `/uploads/notices/${req.file.filename}`;

    res.json({
      success: true,
      fileUrl: fileUrl,
      fileName: req.file.originalname,
      message: '文件上传成功'
    });

  } catch (error) {
    console.error('文件上传失败:', error);
    res.status(500).json({
      success: false,
      message: '文件上传失败',
      error: error.message
    });
  }
});
module.exports = router;